/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdd.dispatchers;

import com.sdd.facades.view.AddressViewFacade;
import com.sdd.facades.view.CheckoutViewFacade;
import com.sdd.plains.AddressPlain;
import com.sdd.plains.CartItem;
import com.sdd.plains.CartPlain;
import com.sdd.plains.CustomerPlain;
import com.sdd.plains.DeliveryPlain;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Properties;
import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fernando
 */
@WebServlet(name = "Checkout", urlPatterns = {"/Checkout"})
public class Checkout extends HttpServlet {
    @EJB
    CheckoutViewFacade checkoutViewFacade;
    @EJB
    AddressViewFacade addressViewFacade;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*    <tr><td>Street:</td><td> <input type="text" name="street"></input></td></tr>
            <tr><td>Number:</td><td> <input type="text" name="number"></input></td></tr>
            <tr><td>Zipcode: </td><td><input type="text" name="zipcode"></input></td></tr>
            <tr><td>City:</td><td> <input type="text" name="city"></input></td></tr>
            <tr><td>Country:</td><td> <input type="text" name="country"></input></td></tr>*/
            CartPlain cartPlain = (CartPlain) request.getSession().getAttribute("cart");
            CustomerPlain customerPlain = (CustomerPlain) request.getSession().getAttribute("customer");
            String street = request.getParameter("street");
            String number = request.getParameter("number");
            String zipcode = request.getParameter("zipcode");
            String city = request.getParameter("city");
            String country = request.getParameter("country");
            String ccnumber = request.getParameter("ccnumber");
            String secnumber = request.getParameter("secnumber");
            
            if(street==null || number==null || zipcode==null || city==null || country==null || ccnumber==null || secnumber==null){
                out.print("Falta algún campo");
            }else{
                AddressPlain addressPlain = new AddressPlain();
                addressPlain.setCity(city);
                addressPlain.setCountry(country);
                addressPlain.setNumber(Integer.parseInt(number));
                addressPlain.setPostCode(Integer.parseInt(zipcode));
                addressPlain.setStreet(street);
                addressPlain = addressViewFacade.addAddress(addressPlain);
                
                System.out.println(addressPlain);
                System.out.println("IDDELUSUARIO "+customerPlain.getId());
                cartPlain = checkoutViewFacade.addCart(cartPlain, customerPlain, addressPlain);
                DeliveryPlain delivery = checkoutViewFacade.getDelivery(addressPlain, cartPlain.getId(),Integer.parseInt(ccnumber),Integer.parseInt(secnumber));
                String print="",printmail="";
                print+="Dear <b>"+customerPlain.getFirstname()+" "+customerPlain.getLastname()+"</b>:<br>";
                printmail+="Dear "+customerPlain.getFirstname()+" "+customerPlain.getLastname()+":\n";
                print+="Soon you will receive an e-mail with your bill.<br>";
                print+="You have bought:<br><ul>";
                printmail+="You have bought:\n";
                Iterator iterator = cartPlain.iterator();
                double total =0;
                while(iterator.hasNext()){
                    CartItem c = (CartItem) iterator.next();
                    total+=c.getQuantity()*c.getProduct().getPrice();
                    print+="<li>"+c.getProduct().getName()+": "+c.getQuantity()+" unit(s) "+c.getQuantity()*c.getProduct().getPrice()+"&euro;</li>";
                    printmail+="- "+c.getProduct().getName()+": "+c.getQuantity()+" unit(s) "+c.getQuantity()*c.getProduct().getPrice()+"€\n";
                }
                print+="</ul><br><b>Total: "+total+" &euro;</b><br>You can visit <a>"+delivery.getWebUrl()+"</a> to track your order";
                printmail+="\nTotal: "+total+" €\nYou can visit "+delivery.getWebUrl()+" to track your order";
                out.print(print);
                sendMail("tiendasdd@gmail.com", "patatapatata", customerPlain.getEmail(), "Your SDD bill", printmail);
                request.getSession().removeAttribute("cart");
            }
        } finally {            
            out.close();
        }
    }

    
    private void sendMail(String desde, String passDesde, String a, String asunto, String cuerpo){
        try
        {
            System.out.println("mail a "+a);
            // Propiedades de la conexión
            Properties props = new Properties();
            props.setProperty("mail.smtp.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.user", desde);
            props.setProperty("mail.smtp.auth", "true");

            // Preparamos la sesion
            Session session = Session.getDefaultInstance(props);

            // Construimos el mensaje
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(desde));
            message.addRecipient(
                Message.RecipientType.TO,
                new InternetAddress(a));
            message.setSubject(asunto);
            message.setText(cuerpo);

            // Lo enviamos.
            Transport t = session.getTransport("smtp");
            t.connect(desde, passDesde);
            t.sendMessage(message, message.getAllRecipients());

            // Cierre.
            t.close();
        }catch(MessagingException m){
            System.out.println(m);
        }
        
    }
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
